简体   繁体   English

动态更改小部件的文本 flutter/dart

[英]Change widget's text dynamically flutter/dart

I tried to script code that generate random value of array and shown on a widget card (every time he's opened will be shown another value from array{string}) In practice, the code choose a cell from array once, and everytime I opened the widget it shows the same one that choose first (without change) I worked with slimycard package ( https://pub.dev/packages/slimy_card )我尝试编写生成数组随机值并显示在小部件卡上的代码(每次他打开时都会显示数组{string}中的另一个值)实际上,代码从数组中选择一个单元格一次,每次我打开小部件它显示与第一个选择相同的小部件(没有变化)我使用 slimycard package ( https://pub.dev/packages/slimy_card )

// in 'homepage' class widget build
child: StreamBuilder(
            initialData: false,
            stream: slimyCard.stream,
            builder: ((BuildContext context, AsyncSnapshot snapshot) {
              return ListView(
                padding: EdgeInsets.only(top: 150),
                children: <Widget>[
                  // SlimyCard is being called here.
                  SlimyCard(
                    color: Colors.transparent.withOpacity(0.2),
                    topCardHeight: 450,
                    width: 400,
                    topCardWidget: topCardWidget(),
                    bottomCardWidget: bottomCardWidget(),
                  ),
                ],
              );
            }),
          )
// the widget I want to change his text every time he's opened.
  Widget bottomCardWidget() {
    return FutureBuilder(
        future: _getfromlist(widget.mode),
        initialData: 'loading..',
        builder: (BuildContext context, AsyncSnapshot<String> text) {
          return new Text(
            text.data,
            style: TextStyle(
              color: Colors.white,
              fontSize: 19,
              fontWeight: FontWeight.w500,
            ),
            textAlign: TextAlign.center,
          );
        });
  }
// _getfromlist func
  Future<String> _getfromlist(int type) async {
    final getter = Random().nextInt(myList[type].length);
    var setter = myList[type][getter];
    var text = '$setter';
    return await new Future(() => text);
  }

Hope you understood my intent.希望你明白我的意图。 Please help, thank you guys:)请大家帮忙,谢谢大家:)

You can copy paste run full code below您可以在下面复制粘贴运行完整代码
Step 1: In initState , listen open/close第 1 步:在initState中,监听打开/关闭

  @override
  void initState() {
    slimyCard.stream.listen((value) {
      if (value) {
        handleFuture();
      }
    });

Step 2: Use ValueNotifier and ValueListenableBuilder to build bottomCardWidget第二步:使用ValueNotifierValueListenableBuilder构建bottomCardWidget

final ValueNotifier<String> _notify = ValueNotifier<String>("");

void handleFuture() async {
    String text = await _getfromlist(1);
    _notify.value = text;
  }
...  
Widget bottomCardWidget() {
    return ValueListenableBuilder(
        valueListenable: _notify,
        builder: (BuildContext context, String value, Widget child) {
          return Text(
            value,
            style: TextStyle(
              color: Colors.white,
              fontSize: 19,
              fontWeight: FontWeight.w500,
            ),
            textAlign: TextAlign.center,
          );
        });
  }  

working demo工作演示

在此处输入图像描述

full code完整代码

import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:slimy_card/slimy_card.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  //Don't worry about these codes here, as they are not relevant for this example.
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    statusBarIconBrightness: Brightness.dark,
    systemNavigationBarColor: Colors.white,
    systemNavigationBarIconBrightness: Brightness.dark,
    systemNavigationBarDividerColor: Colors.transparent,
  ));
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.white,
        fontFamily: 'Poppins',
      ),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final ValueNotifier<String> _notify = ValueNotifier<String>("");

  void handleFuture() async {
    String text = await _getfromlist(1);
    _notify.value = text;
  }

  @override
  void initState() {
    slimyCard.stream.listen((value) {
      if (value) {
        handleFuture();
      }
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
        // This streamBuilder reads the real-time status of SlimyCard.
        initialData: false,
        stream: slimyCard.stream, //Stream of SlimyCard
        builder: ((BuildContext context, AsyncSnapshot snapshot) {
          return ListView(
            padding: EdgeInsets.zero,
            children: <Widget>[
              SizedBox(height: 100),
              SlimyCard(
                // In topCardWidget below, imagePath changes according to the
                // status of the SlimyCard(snapshot.data).
                topCardWidget: topCardWidget((snapshot.data)
                    ? 'https://picsum.photos/250?image=9'
                    : 'https://picsum.photos/250?image=15'),
                bottomCardWidget: bottomCardWidget(),
              )
            ],
          );
        }),
      ),
    );
  }

  // This widget will be passed as Top Card's Widget.
  Widget topCardWidget(String imagePath) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Container(
          height: 70,
          width: 70,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(15),
            image: DecorationImage(image: NetworkImage(imagePath)),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 20,
                spreadRadius: 1,
              ),
            ],
          ),
        ),
        SizedBox(height: 15),
        Text(
          'The Rock',
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        SizedBox(height: 15),
        Text(
          'He asks, what your name is. But!',
          style: TextStyle(
              color: Colors.white.withOpacity(0.8),
              fontSize: 12,
              fontWeight: FontWeight.w500),
        ),
        SizedBox(height: 10),
      ],
    );
  }

  // This widget will be passed as Bottom Card's Widget.
  Widget bottomCardWidget() {
    return ValueListenableBuilder(
        valueListenable: _notify,
        builder: (BuildContext context, String value, Widget child) {
          return Text(
            value,
            style: TextStyle(
              color: Colors.white,
              fontSize: 19,
              fontWeight: FontWeight.w500,
            ),
            textAlign: TextAlign.center,
          );
        });
  }

// _getfromlist func
  Future<String> _getfromlist(int type) async {
    final getter = Random().nextInt(100);
    //var setter = myList[type][getter];
    var text = '$getter';
    return Future.value(text);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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