我在一类中有一个变量,但是我想全部使用它。
在本示例中,是在Muesnterboerse或MuensterboerseAAAngebote中声明的allJobs变量,我想在senddate()中使用它。

class Muensterboerse extends StatelessWidget {
var allJobs = 1;

@override
Widget build(BuildContext context) {
return new MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Flutter App with MYSQL',
  home: new MyHomePage(),

);
}
}

class MuensterboerseAAAngebote extends StatelessWidget {
var allJobs = 0;

@override
Widget build(BuildContext context) {
return new MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Flutter App with MYSQL',
  home: new MyHomePage(),

);
}
}

Future<dynamic> senddata() async {
final response = await http.post(
  "https://www.bumsbirnbe.php", body: {
"status": allJobs,
});



var datauser = json.decode(response.body);

String jsonsDataString = datauser.toString();
dynamic jsonData = jsonDecode(jsonsDataString);

print(jsonData);


return jsonData;
}
更新
现在我将您的更改添加到我的代码中,但是我得到了
错误:未处理的异常:NoSuchMethodError:在空调用getter'allJobs'。
这是我的整个代码:
import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

GlobalKey _key1 = GlobalKey();

class Muensterboerse extends StatelessWidget {
  Muensterboerse({Key key}) : super(key: key);

  int allJobs = 1;

  @override
  Widget build(BuildContext context) {
  return new MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'Flutter App with MYSQL',
  home: new MyHomePage(),

  );
  }
  }

class AAAngebote extends StatelessWidget {
  AAAngebote({Key key}) : super(key: key);

  int allJobs = 2;
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
  title: 'Flutter App with MYSQL',
  home: new MyHomePage(),

    );
  }
}

Future<dynamic> senddata() async {
  int allJobs = (_key1.currentWidget as Muensterboerse).allJobs;
  print(allJobs);

  final response = await http.post(
      "https://www.Bumsbirne.php", body: {
    "status": allJobs,
  });


  var datauser = json.decode(response.body);

  String jsonsDataString = datauser.toString();
  dynamic jsonData = jsonDecode(jsonsDataString);

  print(jsonData);


  return jsonData;
}

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

  final String title;

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


class _MyHomePageState extends State<MyHomePage> {
  dynamic jsonData;


  callSendData() async {
      jsonData = await senddata();
      setState(() {});
  }

//lol
  @override
  void initState() {
    callSendData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: jsonData == null
            ? Center(child: CircularProgressIndicator())
            : ListView.builder(
           padding: const EdgeInsets.all(16.0),
            itemCount: jsonData == null ? 0 : jsonData.length,
            itemBuilder: (context, index) {
              return ListTile(

                leading: CircleAvatar(
                  backgroundImage:     NetworkImage('https://kinsta.com/de/wpcontent/uploads/sites/5/2019/09/wordpress-loggst-url-1024x512.jpg'),
                  radius: 27,
            ),

            title: Text(
              jsonData[index]["titel"],
            ),
            subtitle: Text(jsonData[index]["nam_ersteller"]),
            trailing: Text(
              '25 Km',
              style: TextStyle(color: Colors.grey,
                fontSize: 12,
                decoration: TextDecoration.none,
                fontFamily: 'Roboto',),

            ),
            onTap: () {
              Navigator.push(context,
                  new MaterialPageRoute(builder: (context) =>         DetailPage()));
            },

          );
          // return _buildRow(data[index]);
        }));
  }
}

class DetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Der Job'),
  ),
);
  }
}

最佳答案

您可以在下面复制粘贴运行完整代码
步骤1:您可以使用GlobalKey并传递给Muensterboerse(key: _key1)第2步:在senddata()中,执行(_key1.currentWidget as Muensterboerse).allJobs;程式码片段

GlobalKey _key1 = GlobalKey();
...
class Muensterboerse extends StatelessWidget {
  Muensterboerse({Key key}) : super(key: key);
...
Future<dynamic> senddata() async {
  int allJobs = (_key1.currentWidget as Muensterboerse).allJobs;
  print(allJobs);
...
Muensterboerse(key: _key1),
senddata()的输出
I/flutter (22480): 1
完整的代码
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

GlobalKey _key1 = GlobalKey();

class Muensterboerse extends StatelessWidget {
  Muensterboerse({Key key}) : super(key: key);

  int allJobs = 1;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text("$allJobs"),
      ],
    );
  }
}

Future<dynamic> senddata() async {
  int allJobs = (_key1.currentWidget as Muensterboerse).allJobs;
  print(allJobs);

  /*final response = await http.post(
      "https://www.quyre.de/2/Muensterboerse.N.php", body: {
    "status": allJobs
  });*/
}

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> {
  int _counter = 0;

  void _incrementCounter() async{
    await senddata();
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Muensterboerse(key: _key1),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

10-06 08:02