【问题标题】:Flutter use one Variable in different classes Error: Getter not found: 'allJobs'Flutter 在不同的类中使用一个变量 Error: Getter not found: 'allJobs'
【发布时间】:2020-10-30 01:57:37
【问题描述】:

我在一个类中有一个变量,但我想全部使用它。 在此示例中是在 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:在 null 上调用了 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'),
  ),
);
  }
}

【问题讨论】:

    标签: flutter variables dart


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    第 1 步:您可以使用GlobalKey 并传递给Muensterboerse(key: _key1)
    第二步:在senddata(),做(_key1.currentWidget as Muensterboerse).allJobs;

    代码sn-p

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

    【讨论】:

    • 我试过你的代码,但它演变成一个问题你能帮我解决新问题吗?
    • 在您编辑的代码中,您没有在 MyHomePage 中使用 Muensterboerse(key: _key1)。请复制粘贴并再次运行我的完整代码以进行检查。
    • Muensterboerse 和 AAAngebote 都调用 MyHomePage,您的实际入口点是什么?请使用 MyApp 和 main 发布重现代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多