首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Flutter和Dart,这是实现这一未来的最佳方式吗?

使用Flutter和Dart,这是实现这一未来的最佳方式吗?
EN

Stack Overflow用户
提问于 2019-06-27 02:40:58
回答 1查看 59关注 0票数 0

我知道还有其他方法可以实现这一点,但我想通过initState()使用Future通过SharedPreferences获得一个列表,而不是使用await。下面说明了我想要实现的目标,它确实有效。因为我以前从未使用过这个模式,所以我不确定这是不是最好的方法(不使用await)。有没有更好的不使用await的方法?

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

class _MyHomePageState extends State<MyHomePage> {
  SharedPreferences _prefs;
  String _sMessage1;
  String _sMessage2;
  List<String> _lsCategories;

  @override
  void initState() {
    super.initState();
    Future<void> future = _initPreferences();
    future.then((_) {
      if (_prefs != null) {
        try {
          _lsCategories = _prefs.getStringList("categories") ?? [];
          debugPrint("Categories = $_lsCategories");
          _sMessage2 = "Categories loaded OK";
        } catch (vError) {
          _sMessage2 = ("Error loading categories = $vError");
        }
      }
      setState(() {});
    });
  }

  Future<void> _initPreferences() {
    return SharedPreferences.getInstance().then((prefs) {
      _prefs = prefs;
      _sMessage1 = "Preferences initialized OK";
    }).catchError((vError) {
      _sMessage1 = "Error initializing preferences = ${vError.toString()}";
      _sMessage2 = "Unable to load categories";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _createText(_sMessage1),
            SizedBox(height: 20),
            _createText(_sMessage2),
          ],
        ),
      ),
    );
  }
}

Text _createText(String sText) {
  return Text(sText == null ? "" : sText,
      style: TextStyle(
          color: Colors.red[500], fontWeight: FontWeight.bold, fontSize: 20));
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Future Test',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: "Flutter Future Test"),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56779204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档