简体   繁体   中英

Flutter :- How to display dynamic widgets on screen?

I want to show entered text in scrambled form. ie, each letter of the word need to display in individual Container in a row. For this, I am taking text input, storing it in List<String> and then scrambling it using shuffle() and then using List.generate to return Container with Text , as below:

List<Widget> _generateJumble(String input) {
  inputList = input.split('');
  var shuffleList = inputList.toList()..shuffle();
  print(shuffleList);
  return List<Widget>.generate(shuffleList.length, (int index) {
    return Container(
      width: 50,
      color: Colors.blue,
      child: Text(shuffleList[index].toString(),
        style: TextStyle(color: Colors.white),
      )
    );
  });
}

I am calling above method onTap of a button upon which the scrambled form of the input should be displayed. But I am not sure how to display the result of above method in UI. How should I use this method so that the returning Container based on shuffleList.length will be displayed in UI as below?

RaisedButton(
  onPressed: () {},
  child: Text('Clear'),
    )
  ],
  ),
),
Row(
  children: <Widget>[
    //  ?  _displayJumble()
  ]
)

This is my solution:

1) Press a button, scrable the string and set it to the a list

2) setState and show the list to the user

This is the widget code:

class _MyHomePageState extends State<MyHomePage> {
  List<String> inputList = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Wrap(
        children:  inputList.map((s) {
          return Container(
            width: 50,
            color: Colors.blue,
            child: Text(
              s,
              style: TextStyle(color: Colors.white),
            ),
          );
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            _generateJumble('Random string');
          });
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  List<Widget> _generateJumble(String input) {
    inputList = input.split('');
    inputList = inputList.toList()..shuffle();
    print(inputList);
  }
}

I used the widget Wrap because automatically wrap the widget when there is no space available for it. You can use whatever you like to use.

This is the screen result:

Before press the button: 在按下按钮之前

After press the button: 在此处输入图像描述

Please check the below solution of it, I have used the Wrap widget for it

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutterlearningapp/colors.dart';

class HomeScreen extends StatefulWidget {
  var inputVales;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _HomeScreen();
  }
}

class _HomeScreen extends State<HomeScreen> {
  List<String> charcaterArray = new List<String>();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        appBar: AppBar(
          title: Text("Home"),
        ),
        body: Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(10.0),
              child: TextField(
                decoration: InputDecoration(labelText: 'Enter Words'),
                onChanged: (text) {
                  setState(() {
                    widget.inputVales = text;
                    charcaterArray.clear();
                    for (var i = 0; i < widget.inputVales.length; i++) {
                      var character = widget.inputVales[i];
                      if (character != " ") {
                        charcaterArray.add(character);
                      }
                    }
                  });
                },
              ),
            ),
            Wrap(
              spacing: 6.0,
              runSpacing: 6.0,
              children:
                  List<Widget>.generate(charcaterArray.length, (int index) {
                return Container(
                  height: MediaQuery.of(context).size.height * 0.1,
                  width: MediaQuery.of(context).size.width * 0.1,
                  decoration: BoxDecoration(
                    color: Colors.lightGreen,
                    borderRadius: BorderRadius.all(Radius.elliptical(4.0, 4.0)),
                  ),
                  child: Center(
                    child: Text(
                      charcaterArray[index],
                      style:
                          TextStyle(color: Colors.deepOrange, fontSize: 20.0),
                    ),
                  ),
                );

                /*Chip(
                  label: Text(charcaterArray[index]),
                  onDeleted: () {
                    setState(() {
                      charcaterArray.removeAt(index);
                    });
                  },
                );*/
              }),
            )
          ],
        ));
  }
}

And here is the output of it 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM