颤动动态设置孩子

时间:2018-03-30 11:02:06

标签: android dart flutter

所以我想动态设置GridView的子项,以便我可以在需要时设置它。目前这是全班。

import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/CustomColors.dart';
import 'package:flutter_app/quote/Quote.dart';
import 'package:flutter_app/quote/QuoteView.dart';
import 'package:flutter_app/section/Section.dart';
import 'package:flutter_app/quote/QuoteData.dart';

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

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

  static List<QuoteData> data = [];

  _readJson() async {
    data.clear();
    var url = 'https://www.dropbox.com/s/7k280ca5dktlhoo/quotes.json?dl=1';
    var httpClient = new HttpClient();
    httpClient.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
      return request.close();
    }).then((HttpClientResponse response) {
      response.transform(utf8.decoder).listen((contents) {
        List<Map> decoded = JSON.decode(contents);
        decoded.forEach((m) {
          String url = m["url"];
          String title = m["title"];
          String sectionString = m["section"];
          Section section;
          for (Section element in Section.values) {
            if (element.toString() == "Section." + sectionString) {
              section = element;
            }
          }
          List<Quote> quotes = m["quotes"];
          data.add(new QuoteData(url, title, section, quotes));
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    _readJson();
    return new MaterialApp(
      title: 'Quotes',
      theme: new ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or press Run > Flutter Hot Reload in IntelliJ). Notice that the
        // counter didn't reset back to zero; the application is not restarted.
        primarySwatch: CustomColors.black,
      ),
      home: new MyHomePage(title: 'Quotes'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  static Section currentSection = Section.movies;

  void _onTileClicked(QuoteData quote) {
    Navigator.push(context,
        new MaterialPageRoute(builder: (context) => new QuoteView(quote)));
  }

  List<Widget> _getTiles(Section section) {
    final List<Widget> tiles = <Widget>[];
    for (var i in MyApp.data) {
      if (i.section != section) {
        continue;
      }
      tiles.add(new GridTile(
          child: new InkResponse(
        enableFeedback: true,
        child: new Image.network(
          i.url,
          fit: BoxFit.cover,
        ),
        onTap: () => _onTileClicked(i),
      )));
    }
    return tiles;
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
    final double itemWidth = size.width / 2;
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return new Scaffold(
      appBar: new AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: new Text(currentSection
                .toString()
                .replaceAll("Section.", "")
                .substring(0, 1)
                .toUpperCase() +
            currentSection.toString().replaceAll("Section.", "").substring(1)),
      ),
      body: new Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: new GridView.count(
            crossAxisCount: 2,
            childAspectRatio: (itemWidth / itemHeight),
            padding: const EdgeInsets.all(4.0),
            mainAxisSpacing: 4.0,
            crossAxisSpacing: 4.0,
            children: _getTiles(currentSection)),
      ),
    );
  }
}

所以现在在启动时,它会启动应用程序,但MyApp.data为空,因为必须读取json,因此GridView将为空,当我刷新应用程序时,GridView将不会为空,因为MyApp.data不再是空的。我希望能够在json被读取之后设置子节点,我也需要能够动态地更改它,因为我将添加一个用于切换节的函数。

标题也是如此,我还需要能够在切换部分时动态地更改它。

1 个答案:

答案 0 :(得分:1)

您可以创建加载小部件并等待请求完成后请求完成隐藏加载并显示网格而不是重建状态。但你需要有一个statefullWidget而不是statelessWidget。

你可以在下面的代码中看到我如何使用它我将我的注释添加到代码

class _ChildrenPageState extends State<ChildrenPage>  {
  //declare the _load to true so it will show the loading when the page is loaded
  bool _load = true;
  ChildrenService _childrenService = new ChildrenService();
  List children = [];

  //I call the _rebuild function to rebuild the widgets and show the data
  void _rebuild() {
    setState(() {
    });
  }

  @override
  Widget build(BuildContext context) {
    //I call the request to get my data when it is finished i put _load to false so the loading will hide and call the _rebuild function to rebuild the widgets and i have put if so when the widget is built it will not rebuild it a second time.

    _childrenService.getChildren(children).then((data){
      if(data && _load){
        _load = false;
        _rebuild();
      }
    });

    //the below widget show the loading container if _load is true else it will show the dataTable in your app you should add the grid and you can pass the data that you got from the request

    Widget loadingIndicator = _load ? new Container(
      color: Colors.grey[300],
      width: 70.0,
      height: 70.0,
      child: new Padding(
          padding: const EdgeInsets.all(5.0),
          child: new Center(
              child: new CircularProgressIndicator()
          )
      ),
    ) : new JLDataTable(
      data: children,
    );

    return new Scaffold(
        drawer: new Drawer(
          child: MenuList.menuList,
        ),
        appBar: new AppBar(title: const Text('Data tables')),
        body: new ListView(
            padding: const EdgeInsets.all(20.0),
            children: <Widget>[
                new Align(
                    child: loadingIndicator,
                    alignment: FractionalOffset.center
                )
            ]
        )
    );
  }
}