【问题标题】:Placing a device model in a Text widget将设备模型放置在文本小部件中
【发布时间】:2019-06-04 21:00:13
【问题描述】:

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

我尝试使用 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 字符串。我知道返回类型是 Future,所以我尝试使用未来构建器来获取值。但现在我很茫然。尝试_getModel().then(value)不行,所以不知道怎么提取设备型号。

【问题讨论】:

    标签: flutter dart future


    【解决方案1】:

    来自 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;
      },
    )
    

    【讨论】:

    • 非常感谢!
    • 很高兴为您提供帮助! -
    猜你喜欢
    • 2011-03-14
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 2018-07-20
    • 2022-09-28
    • 2023-02-07
    相关资源
    最近更新 更多