Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter loop inside a widget

Tags:

flutter

dart

I'm new to flutter and was wondering if anyone would be able to guide me.

I would like to irritate through a string that I retrieved from a json file. I would like to display each letter separately. Example below.

Output Complete Word: Hi Letter pos 0: H Letter pos 1: I

What I tried so far is adding a for loop below the itemBuilder but can't retrieve the variable inside the card. I tried adding a for loop inside the Widget and it doesn't allow me.

Any input would be greatly appreciated!

import 'dart:convert';

import 'package:flutter/material.dart';


void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {
  List data;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Load local JSON file"),
        ),
        body: new Container(
          child: new Center(
            // Use future builder and DefaultAssetBundle to load the local JSON file
            child: new FutureBuilder(
                future: DefaultAssetBundle
                    .of(context)
                    .loadString('data_repo/starwars_data.json'),
                builder: (context, snapshot) {
                  // Decode the JSON
                  var new_data = JSON.decode(snapshot.data.toString());

                  return new ListView.builder(
                    // Build the ListView

                    itemBuilder: (BuildContext context, int index) { 
                      return new Card(
                        child: new Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: <Widget>[
                            new Text("Complete Word: " + new_data[index]['complete_word'])
                          ],
                        ),
                      );
                    },
                    itemCount: new_data == null ? 0 : new_data.length,
                  );
                }),
          ),
        ));
  }
}
like image 998
Ouardia Avatar asked Apr 08 '18 20:04

Ouardia


1 Answers

Create a method and within it create a list of widgets. Include the widgets and then return the list.

Example

child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: ListMyWidgets()),

List<Widget> ListMyWidgets() {
List<Widget> list = new List();
list.add(new Text("hi"));
list.add(new Text("hi2"));
list.add(new Text("hi3"));
return list;
}
like image 181
Ouardia Avatar answered Sep 24 '22 02:09

Ouardia