3

I read carefully the Flutter tutorial; Fetching data from internet: https://flutter.io/cookbook/networking/fetch-data/

My concern is that I want to update multiple texts in my layout.

The implementation only shows a way to update one:

FutureBuilder<Post>(
  future: fetchPost(),
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
    // By default, show a loading spinner
    return CircularProgressIndicator();
  },
);

This works fine and displays one view at a time.

In Android Studio/Java, I would have done something like:

myTextView1.setText(snapshot.data.data1)
myTextView2.setText(snapshot.data.data2)
myTextView3.setText(snapshot.data.data3)
.....
myTextView10.setText(snapshot.data.data3)

But here in Flutter, I am currently limited to one "Widget" at a time.

Of course, I could provide my whole layout in the return argument, but that would be crazy!

Any idea/suggestion?

Waza_Be
  • 39,407
  • 49
  • 186
  • 260
  • 1
    You'll want an inheritedwidget. See https://stackoverflow.com/questions/49491860/flutter-how-to-correctly-use-an-inherited-widget/49492495#49492495 for their usage – Rémi Rousselet Oct 12 '18 at 08:16
  • Do you want to have multiple loading indicators, too? – cy3er Oct 12 '18 at 10:03

2 Answers2

1

An alternative strategy is to have a local variable in the state class and update it when the future arrives. Thus, you can reference that variable wherever you need.

Here is an example:

import 'dart:async';

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  Post _post = Post("Title 0", "Subtitle0 ", "description 0");

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

  void _getPost() async {
    _post = await fetchPost();
    setState(() {});
  }

  Future<Post> fetchPost() {
    return Future.delayed(Duration(seconds: 4), () {
      return Post("Title new", "Subtitle new", "description new");
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: Center(
        child: Column(
          children: <Widget>[
            new Text(_post.title),
            new Text(_post.subtitle),
            new Text(_post.description),
          ],
        ),
      ),
    );
  }
}

class Post {
  final String title;
  final String subtitle;
  final String description;

  Post(this.title, this.subtitle, this.description);
}
chemamolins
  • 19,400
  • 5
  • 54
  • 47
1

You can convert your request to Stream

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

class TestWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(child: RandomContainer(
        width: 200.0,
        height: 200.0,
        child: Center(child: _MyTextWidget(fetchPost().asStream())),
      ),),
    );
  }

  Future<String> fetchPost() {
    return Future.delayed(Duration(seconds: 4), () {
      return "Title data";
    });
  }

}
class _MyTextWidget extends StatefulWidget {
  _MyTextWidget(this.stream);
  final Stream<String> stream;

  @override
  State<StatefulWidget> createState() => _MyTextWidgetState();
}

class _MyTextWidgetState extends State<_MyTextWidget> {

  String text;

  @override
  void initState() {
    widget.stream.listen((String data) {
      setState(() {
        text = data;
      });
    });
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Text(text == null ? 'loading' : text);
  }

}

In this example RandomContainer changes its color on every setState and it works as indicator, than changes are only in _MyTextWidget

Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105