8-flutter 异步和线程

线程和异步的UI

1 异步的使用

Dart 有一个单线程执行模型,支持Isolate(一种在另外一种线程运行dart的方法),一个事件循环和异步编程。

可以使用async / await 来做网络请求不会挂起UI

使用http 导入

import ‘dart:io’;

import ‘dart:convert’;

// 加载数据
dataHandle()async{

    String url = "https://www.apiopen.top/journalismApi";
    var responseBody;
    var http = new HttpClient();
    var request = await http.getUrl(Uri.parse(url));
    var response = await request.close();
    if (response.statusCode == 200){
        print("Success");
        responseBody = await response.transform(utf8.decoder).join();
        print(responseBody);
    }else{
        print("error happend");
    }
}

2 网络请求数据 加载到列表中去

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'dart:convert';
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: SampleAppPage(),

    );
  }
}

class SampleAppPage extends StatefulWidget{
    SampleAppPage({Key key}) : super(key:key);
    @override
    _SampleAppPageState createState() =>  _SampleAppPageState();
    
}

class _SampleAppPageState extends State
{
    List widgets =[]; 
   // 加载数据
    dataHandle()async{

        String url = "https://www.apiopen.top/journalismApi";
        var responseBody;
        var http = new HttpClient();
        var request = await http.getUrl(Uri.parse(url));
        var response = await request.close();
        if (response.statusCode == 200){
          print("Success");
          responseBody = await response.transform(utf8.decoder).join();
          responseBody = json.decode(responseBody);
          // 通过调用setState 方式来更新UI
          setState(() {
            widgets = responseBody["data"]["tech"];
            print(widgets.length);
          });   
        }else{
          print("error happend");
        }
    }

    // 初始化状态的时候加载数据
    @override
    void initState() {
        super.initState();
        dataHandle();
    }

    Widget getRow (int idx){
        return Padding(
            padding: EdgeInsets.all(10),
            child: Text("${widgets[idx]["title"]}",
            style: new TextStyle(fontSize: 22,color: Colors.green),),
        );
    }

    @override 
    Widget build(BuildContext context){

      return Scaffold(
          appBar: AppBar(title: new Text("Hello World")),
          body: ListView.builder(
            itemCount: widgets.length,
            itemBuilder: (BuildContext context,int idx){
                return getRow(idx);
            },
          ),
      );
    }
}



 

8-flutter 异步和线程_第1张图片

你可能感兴趣的:(flutter基础,Flutter,基础)