Flutter Widget创建时运行异步操作

样例代码

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    return MaterialApp(
        home: Scaffold(
      body: Center(child: AsyncTest()),
    ));
  }
}

class AsyncTest extends StatefulWidget {
  @override
  _AsyncTestState createState() => _AsyncTestState();
}

int getNumber(int n) {
  if (n == 0) {
    return 0;
  } else if (n == 1) {
    return 1;
  } else {
    return getNumber(n - 1) + getNumber(n - 2);
  }
}

Future loadAsset(BuildContext context) async {
  return await DefaultAssetBundle.of(context)
      .loadString('assets/novels/0-1.txt');
}

class _AsyncTestState extends State {
  bool loading = true;

  @override
  void initState() {
    super.initState();

    loadAsset(context).then((result) {
      debugPrint(
          'consume cpu time function result is ' + getNumber(20).toString());

      Future.delayed(Duration(seconds: 1)).then((result) {
        setState(() {
          loading = false;
        });
      });
    });
  }


  
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    if (loading == true) {
      return CircularProgressIndicator();
    }

    return Text('load finished ');
  }
}


几点说明:

  1. 使用StatefulWidget 有状态Widget
  2. 在initState函数中执行异步操作
  3. 保证在已有结果的状态下调用setState

 

 

参考:

https://flutter.institute/run-async-operation-on-widget-creation/

 

Comment

*

沪ICP备14014813号

沪公网安备 31010802001379号