如何从子无状态小部件设置有状态小部件的状态

时间:2020-11-03 18:50:51

标签: flutter dart

好吧,只为警告您,我15岁,我是个完全颤抖的菜鸟。这是我有史以来的第一个项目,请原谅可能是愚蠢的问题,请对我保持轻松。 我有这个有状态的小部件(ride),其中主体是_children中定义的子无状态小部件之一。 if语句仅在第一个和第二个子窗口小部件之间改变,具体取决于用户是否连接了BT设备(该部分无关紧要)。 我需要做的是从ln 68上的MaterialButton内部设置状态,以便ride显示riding无状态小部件,但显然我不能从startRide之内,因为它是无状态的小部件。我将如何去做?

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' ;
import 'results.dart';
import 'settings.dart';


class ride extends StatefulWidget {
  @override
  _rideState createState() => _rideState();
}

class _rideState extends State<ride> {
  int _currentState = 0;
  final List<Widget> _children = [
    notConnected(),
    startRide(),
    riding(),
  ];

  bool connected = checkBT(); // Function defined in settings.dart


  @override
  Widget build(BuildContext context) {
    if (connected == true){
      _currentState = 1;
      setState((){_currentState;});
    }
    return _children[_currentState];
  }
}

class notConnected extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Container(
        height:180,
        padding: EdgeInsets.fromLTRB(40, 0, 40, 0),
        child: Center(
          child: Text(
            "Oops! Looks like your phone isn’t connected to your bluetooth device.",
            style:Theme.of(context).textTheme.bodyText2,
            textAlign: TextAlign.center,
          ),
        ),
      ),

    );
  }
}

class startRide extends StatelessWidget {
  AudioPlayer _audioPlayer = AudioPlayer();
  AudioCache player = AudioCache();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Center(
        child: Container(
          width: 200,
          height: 80,
          child: MaterialButton(
            onPressed:(){
              player.play("beeps.mp3");
              // I NEED TO SET THE STATE OF RIDE HERE
            },

            child: Text(
              "Start!",
              style: Theme.of(context).textTheme.headline1,
            ),
            color: Colors.red[500],
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(40.0)),


          ),
      ),
      ),
      ),
    );

  }

}

class riding extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(); //not finished writing this yet
  }
}

我可能会以完全错误的方式进行此操作,但是我来自python,所以它非常不同。任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:1)

您可以创建回调,即传递函数

这是示例代码

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' ;
import 'results.dart';
import 'settings.dart';


class ride extends StatefulWidget {
  @override
  _rideState createState() => _rideState();
}

class _rideState extends State<ride> {
  int _currentState = 0;
  final List<Widget> _children = [
    notConnected(),
    startRide((){
      // you can setState((){}) here
    }),
    riding(),
  ];

  bool connected = checkBT(); // Function defined in settings.dart


  @override
  Widget build(BuildContext context) {
    if (connected == true){
      _currentState = 1;
      setState((){_currentState;});
    }
    return _children[_currentState];
  }
}

class notConnected extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: Container(
        height:180,
        padding: EdgeInsets.fromLTRB(40, 0, 40, 0),
        child: Center(
          child: Text(
            "Oops! Looks like your phone isn’t connected to your bluetooth device.",
            style:Theme.of(context).textTheme.bodyText2,
            textAlign: TextAlign.center,
          ),
        ),
      ),

    );
  }
}

class startRide extends StatelessWidget {
  AudioPlayer _audioPlayer = AudioPlayer();
  AudioCache player = AudioCache();
  Function callback;

  startRide(Function callback){
     this.callback = callback;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Center(
        child: Container(
          width: 200,
          height: 80,
          child: MaterialButton(
            onPressed:(){
              player.play("beeps.mp3");
              // I NEED TO SET THE STATE OF RIDE HERE
              // callback function
              callback();
            },

            child: Text(
              "Start!",
              style: Theme.of(context).textTheme.headline1,
            ),
            color: Colors.red[500],
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(40.0)),


          ),
      ),
      ),
      ),
    );

  }

}

class riding extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(); //not finished writing this yet
  }
}

编辑:-测试代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Test(),
    );
  }
}

class Test extends StatefulWidget {
  @override
  _Test createState() => _Test();
}

class _Test extends State<Test> {

  int current = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: root(),
    );
  }

  Widget root() {
    return Container(
      child: TestingStateless((){
        setState(() {
          current++;
          print(current);
        });
      }),
    );
  }
}

// ignore: must_be_immutable
class TestingStateless extends StatelessWidget{
  Function func;

  TestingStateless(Function func){
    this.func = func;
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: (){
        func();
      },
      child: Container(
        height: 50,
        color: Colors.green,
        child: Text('TESTING'),
      ),
    );
  }
}