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/

 


Posted

in

by

Tags:

Comments

2 responses to “Flutter Widget创建时运行异步操作”

  1. lee Avatar
    lee

    https://www.askmaclean.com/archives/ 这个链接最下面的page 页好像没办法跳转

    1. admin Avatar
      admin

      https://www.askmaclean.com/page/2 请用这样的跳转 archives那个是有问题。

Leave a Reply to lee Cancel reply

Your email address will not be published. Required fields are marked *