将设备模型放置在文本小部件中

Placing a device model in a Text widget

我需要在文本小部件中打印我的设备型号。

我尝试使用 FutureBuilder 小部件来获取设备型号。

import 'package:flutter/material.dart';
import 'package:device_info/device_info.dart';

class DeviceInfoPage extends StatelessWidget {
  String s;
  Future _getModel() async{
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
    return androidInfo.model;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          FutureBuilder(
            future: _getModel(),
            builder: (BuildContext context, AsyncSnapshot snap) {
              if(snap.hasData) {}
              else {}
            }
          ),
        ],
      ),
    );
  }
}

我正在尝试从 _getModel 方法中获取 androidInfo.model 字符串。我知道 return 类型是 Future,所以我尝试使用 future builder 来获取值。但现在我不知所措。尝试 _getModel().then(value) 不行,所以我不知道如何提取设备型号。

来自 snap 参数。我想你可以这样做:

FutureBuilder(
    future: _getModel(),
    builder: (BuildContext context, AsyncSnapshot<String> snap) {
      if(snap.hasData) {
        Text('Model: ${snap.data}')
      } else {
        Text('Awaiting model...')
      }
    }
),

建议检查连接状态。查看 docs example 以获取更多信息,并可能重构为类似的内容:

FutureBuilder<String>(
  future: _getModel(), 
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.active:
      case ConnectionState.waiting:
        return Text('Awaiting result...');
      case ConnectionState.done:
        if (snapshot.hasError)
          return Text('Error: ${snapshot.error}');
        return Text('Result: ${snapshot.data}');
    }
    return null;
  },
)