简体   繁体   English

如何将整数从子小部件传递给父小部件?

[英]How do I pass an integer from a child widget to the parent widget?

I'm in the process of making a custom navigation bar for my project, and need to pass the current page # from the child navigation bar widget, to the main page.我正在为我的项目制作自定义导航栏,并且需要将当前页面 # 从子导航栏小部件传递到主页。 I can't seem to figure out the best method for transferring the int.我似乎无法找出传输 int 的最佳方法。

Custom navigation bar with int needed to be accessed:需要访问带有 int 的自定义导航栏:

import 'package:flutter/material.dart';
import 'package:my_app/theme.dart';

class CustomNavBar extends StatefulWidget {
  const CustomNavBar({Key? key}) : super(key: key);

  @override
  State<CustomNavBar> createState() => _CustomNavBarState();
}

class _CustomNavBarState extends State<CustomNavBar> {
  //Need to pass this int to parent
  int currentPage = 0;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(0),
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24),
          topRight: Radius.circular(24),
        ),
      ),
      color: primaryColor,
      child: Row(
        children: <Widget>[
          Expanded(child: navBarItem(0, Icons.home)),
          Expanded(child: navBarItem(1, Icons.looks_one_rounded)),
          Expanded(child: navBarItem(2, Icons.looks_two_rounded)),
          Expanded(child: navBarItem(3, Icons.looks_3_rounded)),
        ],
      ),
    );
  }

  Widget navBarItem(
    int index,
    IconData icon,
  ) {
    return GestureDetector(
      onTap: () {
        setState(() {
          currentPage = index;
        });
      },
      child: Container(
        height: 80,
        width: MediaQuery.of(context).size.width / 4,
        decoration: const BoxDecoration(
          color: Colors.transparent,
        ),
        child: Icon(
          icon,
          color: index == currentPage ? Colors.white : primaryAccentColor,
        ),
      ),
    );
  }
}

Main.dart where int is needed to be accessed:需要访问 int 的 Main.dart:

import 'package:flutter/material.dart';
import 'package:my_app/Pages/home_page.dart';
import 'package:my_app/Pages/profile_page.dart';
import 'package:my_app/Pages/testing_page.dart';
import 'package:my_app/Pages/testing_page2.dart';
import 'package:my_app/widgets/custom_navbar_widget.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: RootPage(),
    );
  }
}

class RootPage extends StatefulWidget {
  const RootPage({Key? key}) : super(key: key);

  @override
  State<RootPage> createState() => _RootPageState();
}

class _RootPageState extends State<RootPage> {
  //Replace this int with the one set from CustomNavBar
  int currentPage = 0;

  List<Widget> pages = [
    const HomePage(),
    const ProfilePage(),
    const TestingPage(),
    const TestingPage2(),
  ];
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        extendBody: true,
        body: pages[currentPage],
        bottomNavigationBar: CustomNavBar(),
      ),
    );
  }
}

You can use a ValueChange .您可以使用ValueChange Actually, this is a signature for callbacks that report that an underlying value has changed.实际上,这是报告基础值已更改的回调的签名。

Look at the implementation :看看实现:

typedef ValueChanged<T> = void Function(T value);

Also, you can use it in the child class like this :此外,您可以像这样在子类中使用它:

import 'package:flutter/material.dart';
import 'package:my_app/theme.dart';

class CustomNavBar extends StatefulWidget {
  const CustomNavBar({Key? key, required this.onItemSelect}) : super(key: key);

  final ValueChanged<int> onItemSelect;

  @override
  State<CustomNavBar> createState() => _CustomNavBarState();
}

class _CustomNavBarState extends State<CustomNavBar> {
  //Need to pass this int to parent
  int currentPage = 0;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.all(0),
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24),
          topRight: Radius.circular(24),
        ),
      ),
      color: primaryColor,
      child: Row(
        children: <Widget>[
          Expanded(child: navBarItem(0, Icons.home)),
          Expanded(child: navBarItem(1, Icons.looks_one_rounded)),
          Expanded(child: navBarItem(2, Icons.looks_two_rounded)),
          Expanded(child: navBarItem(3, Icons.looks_3_rounded)),
        ],
      ),
    );
  }

  Widget navBarItem(
    int index,
    IconData icon,
  ) {
    return GestureDetector(
      onTap: () {
        setState(() {
          widget.onItemSelect(currentPage);
          currentPage = index;
        });
      },
      child: Container(
        height: 80,
        width: MediaQuery.of(context).size.width / 4,
        decoration: const BoxDecoration(
          color: Colors.transparent,
        ),
        child: Icon(
          icon,
          color: index == currentPage ? Colors.white : primaryAccentColor,
        ),
      ),
    );
  }
}

And check for new changes in parent, like this :并检查父项中的新更改,如下所示:

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: RootPage(),
    );
  }
}

class RootPage extends StatefulWidget {
  const RootPage({Key? key}) : super(key: key);

  @override
  State<RootPage> createState() => _RootPageState();
}

class _RootPageState extends State<RootPage> {
  //Replace this int with the one set from CustomNavBar
  int currentPage = 0;

  List<Widget> pages = [
    const HomePage(),
    const ProfilePage(),
    const TestingPage(),
    const TestingPage2(),
  ];
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        extendBody: true,
        body: pages[currentPage],
        bottomNavigationBar: CustomNavBar(onItemSelect: (value) => print(value),),
      ),
    );
  }
}

For more detail, please check : https://api.flutter.dev/flutter/foundation/ValueChanged.html详情请查看: https ://api.flutter.dev/flutter/foundation/ValueChanged.html

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

相关问题 如何将数据从子小部件传递到父小部件 - How can i pass data from a child widget to a parent widget 将数据从子小部件传递到父小部件 - Pass data from child widget to the parent widget 如何将数据从子状态小部件传递到 Flutter 中的父小部件 - How to pass data from a child Stateful widget to Parent Widget in Flutter 如何将变量传递给子小部件? - How do I pass a variable to a child widget? 如何从父小部件调用子小部件的 setState? - How can I call setState of a child widget from a parent widget? Flutter - 如何从子小部件调用父小部件函数,同时还使用变量保持状态? - Flutter - How do I call a Parent widget function from child widget while also maintaining the state with a variable? 如何将数据从子小部件传递到其父小部件 - How to pass data from child widget to its parent 如何将父小部件的高度传递给 flutter 中的子小部件? - How to pass the height of parent widget to child widget in flutter? Flutter:当小部件没有父/子关系时,如何从小部件 B 调用小部件 A 中的 function? - Flutter: How do I call a function in widget A from widget B when the widgets do not have a parent/child relationship? 如何使用 flutter 中的提供程序或 valuenotifier 将数据从子小部件传递到父小部件 - How to pass data from child widget to parent widget using provider or valuenotifier in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM