栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

来自Flutter中的PHP的API流(非Firebase)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

来自Flutter中的PHP的API流(非Firebase)

请参考此文档https://blog.khophi.co/using-refreshindicator-with-flutter-
streambuilder/

还有一个视频

github代码https://github.com/seanmavley/refreshindicator-with-
streambuilder/blob/master/lib/main.dart

完整的示例代码

import 'package:flutter/material.dart';import 'package:http/http.dart' as http;import 'dart:async';import 'dart:convert';void main() => runApp(new MyApp());class MyApp extends StatelessWidget {  @override  Widget build(BuildContext context) {    return new MaterialApp(      debugShowCheckedModeBanner: false,      title: 'Basic Project',      home: new MyHomePage(),    );  }}class MyHomePage extends StatefulWidget {  @override  _MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {  StreamController _postsController;  final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();  int count = 1;  Future fetchPost([howMany = 5]) async {    final response = await http.get(        'https://blog.khophi.co/wp-json/wp/v2/posts/?per_page=$howMany&context=embed');    if (response.statusCode == 200) {      return json.depre(response.body);    } else {      throw Exception('Failed to load post');    }  }  loadPosts() async {    fetchPost().then((res) async {      _postsController.add(res);      return res;    });  }  showSnack() {    return scaffoldKey.currentState.showSnackBar(      SnackBar(        content: Text('New content loaded'),      ),    );  }  Future<Null> _handleRefresh() async {    count++;    print(count);    fetchPost(count * 5).then((res) async {      _postsController.add(res);      showSnack();      return null;    });  }  @override  void initState() {    _postsController = new StreamController();    loadPosts();    super.initState();  }  @override  Widget build(BuildContext context) {    return new Scaffold(      key: scaffoldKey,      appBar: new AppBar(        title: new Text('StreamBuilder'),        actions: <Widget>[          IconButton( tooltip: 'Refresh', icon: Icon(Icons.refresh), onPressed: _handleRefresh,          )        ],      ),      body: StreamBuilder(        stream: _postsController.stream,        builder: (BuildContext context, AsyncSnapshot snapshot) {          print('Has error: ${snapshot.hasError}');          print('Has data: ${snapshot.hasData}');          print('Snapshot Data ${snapshot.data}');          if (snapshot.hasError) { return Text(snapshot.error);          }          if (snapshot.hasData) { return Column(   children: <Widget>[     Expanded(       child: Scrollbar(         child: RefreshIndicator(onRefresh: _handleRefresh,child: ListView.builder(  physics: const AlwaysScrollableScrollPhysics(),  itemCount: snapshot.data.length,  itemBuilder: (context, index) {    var post = snapshot.data[index];    return ListTile(      title: Text(post['title']['rendered']),      subtitle: Text(post['date']),    );  },),         ),       ),     ),   ], );          }          if (snapshot.connectionState != ConnectionState.done) { return Center(   child: CircularProgressIndicator(), );          }          if (!snapshot.hasData &&   snapshot.connectionState == ConnectionState.done) { return Text('No Posts');          }        },      ),    );  }}

您的json类在PHP

// To parse this JSON data, do////     final payload = payloadFromJson(jsonString);import 'dart:convert';List<Payload> payloadFromJson(String str) => new List<Payload>.from(json.depre(str).map((x) => Payload.fromJson(x)));String payloadToJson(List<Payload> data) => json.enpre(new List<dynamic>.from(data.map((x) => x.toJson())));class Payload {    int userId;    int id;    String title;    String body;    Payload({        this.userId,        this.id,        this.title,        this.body,    });    factory Payload.fromJson(Map<String, dynamic> json) => new Payload(        userId: json["userId"],        id: json["id"],        title: json["title"],        body: json["body"],    );    Map<String, dynamic> toJson() => {        "userId": userId,        "id": id,        "title": title,        "body": body,    };}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/483258.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号