简体   繁体   中英

How to set the state of a stateful widget from a child stateless widget

Okay, so just to warn you, I'm 15 and I'm a complete flutter noob. This is my first ever project, so excuse the probably dumb question, and please go easy on me. I have this stateful widget ( ride ) where the body is one of the child stateless widgets defined in _children . The if statement just changes between the 1st and 2nd child widgets depending on if the user has connected a BT device (that part is irrelevant). What I need to do is set the state from the inside of the MaterialButton found on ln 68 so that ride shows the riding stateless widget, but obviously I can't change the state from inside startRide because it's a stateless widget. How would I go about doing this?

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
  }
}

I'm probably going about doing this in completely the wrong way, but I've come from python so it's very different. Any help would be greatly appreciated :)

You can create callback, ie passing function

Here is a sample code

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
  }
}

Edit :- Test code

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'),
      ),
    );
  }
}

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