首页 > 解决方案 > 如何更改 State of class 中的 bool 扩展?

问题描述

如何从外部访问更新方法?我需要更改expand,因为这是在 a 中ListView,如果它是集中的,我想更改颜色和大小(尚未实现)之类的东西。有人知道怎么做吗?
也许如果您知道是否有一个小部件可以改变其子项的大小而不是高度和宽度,而是像缩放一样?这样它的所有孩子都会变大一个因素。

import 'package:flutter/material.dart';
import 'package:tastie/models/Cuisine.dart';
import 'package:tastie/models/Restaurant.dart';
import 'package:tastie/style.dart';

class RestaurantPreview extends StatefulWidget {
  final BuildContext context;
  final Restaurant resto;

  RestaurantPreview(this.context, this.resto);

  @override
  _RestaurantPreviewState createState() => _RestaurantPreviewState(false);
}

class _RestaurantPreviewState extends State<RestaurantPreview> {
  bool expand;

  void update(bool x) {
    setState(() {
      expand = x;
    });
  }
  _RestaurantPreviewState(this.expand);
  @override
  Widget build(BuildContext context) {
    return Container(
      color: expand ? Colors.red : Colors.white,
      child: Padding(
        padding: EdgeInsets.all(10),
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width / 1.6,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //image of restaurnt via id
              Flex(
                direction: Axis.horizontal,
                children: [
                  Padding(
                    padding: EdgeInsets.only(right: 4),
                    child: Text(
                      widget.resto.name,
                      style: Style.homeFeedTextStyleName,
                    ),
                  ),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(2),
                    child: Image(
                      image: widget.resto.logo.image,
                      height: Style.homeFeedTextStyleName.fontSize *
                          (MediaQuery.of(context).textScaleFactor + 0.4),
                    ),
                  ),
                ],
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(Style.homeFeedRadius),
                child: widget.resto.image,
              ),
              Text(
                widget.resto.description,
                style: Style.homeFeedTextStyleDescription,
              ),
              Wrap(
                spacing: 5.0,
                alignment: WrapAlignment.start,
                direction: Axis.horizontal,
                children: [
                  for (int cuisine in widget.resto.cuisines)
                    Chip(
                      label: Text(Cuisine.getName(cuisine)),
                    )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

标签: flutterdart

解决方案


您可以在下面复制粘贴运行完整代码
您可以使用GlobalKey获取_RestaurantPreviewState和调用update函数

GlobalKey _key = GlobalKey();

RestaurantPreview(
              key: _key,
              context: context,
              resto: Restaurant(
                  name: "name",
                  logoImage: "https://picsum.photos/250?image=9",
                  image: "https://picsum.photos/250?image=10",
                  description: "desc",
                  cuisines: ["1", "2", "3"]),
            ),
RaisedButton(
              child: Text('expand true'),
              onPressed: () {
                final _RestaurantPreviewState previewState = _key.currentState;
                previewState.update(true);
              },
            ),

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';

class Restaurant {
  String name;
  String logoImage;
  String image;
  String description;
  List<String> cuisines;

  Restaurant(
      {this.name, this.logoImage, this.image, this.description, this.cuisines});
}

class RestaurantPreview extends StatefulWidget {
  final BuildContext context;
  final Restaurant resto;

  RestaurantPreview({Key key, this.context, this.resto}) : super(key: key);

  @override
  _RestaurantPreviewState createState() => _RestaurantPreviewState(false);
}

class _RestaurantPreviewState extends State<RestaurantPreview> {
  bool expand;

  void update(bool x) {
    setState(() {
      expand = x;
    });
  }

  _RestaurantPreviewState(this.expand);
  @override
  Widget build(BuildContext context) {
    return Container(
      color: expand ? Colors.red : Colors.white,
      child: Padding(
        padding: EdgeInsets.all(10),
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width / 1.6,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //image of restaurnt via id
              Flex(
                direction: Axis.horizontal,
                children: [
                  Padding(
                    padding: EdgeInsets.only(right: 4),
                    child: Text(
                      widget.resto.name,
                      //style: Style.homeFeedTextStyleName,
                    ),
                  ),
                  ClipRRect(
                    borderRadius: BorderRadius.circular(2),
                    child: Image(
                      image: NetworkImage(widget.resto.logoImage),
                      height: 100,
                    ),
                  ),
                ],
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(30),
                child: Image.network(widget.resto.image),
              ),
              Text(
                widget.resto.description,
                //style: Style.homeFeedTextStyleDescription,
              ),
              Wrap(
                spacing: 5.0,
                alignment: WrapAlignment.start,
                direction: Axis.horizontal,
                children: [
                  for (String cuisine in widget.resto.cuisines)
                    Chip(
                      label: Text("$cuisine"),
                    )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey _key = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RestaurantPreview(
              key: _key,
              context: context,
              resto: Restaurant(
                  name: "name",
                  logoImage: "https://picsum.photos/250?image=9",
                  image: "https://picsum.photos/250?image=10",
                  description: "desc",
                  cuisines: ["1", "2", "3"]),
            ),
            RaisedButton(
              child: Text('expand true'),
              onPressed: () {
                final _RestaurantPreviewState previewState = _key.currentState;
                previewState.update(true);
              },
            ),
            RaisedButton(
              child: Text('expand false'),
              onPressed: () {
                final _RestaurantPreviewState previewState = _key.currentState;
                previewState.update(false);
              },
            ),
          ],
        ),
      ),
    );
  }
}

推荐阅读