我需要在其他类(状态类)中获取函数,而我的代码在第一类中:

import 'package:flutter/material.dart';

class Search extends StatefulWidget {
  final Widget child;
  Search({Key key, this.child}) : super(key: key);
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search> {
   _title(){
      return 'Lorem Ipsum Title';
   }

   @override
   Widget build(BuildContext context) {
      //...
   }
}

然后在第二节课中:
import 'package:flutter/material.dart';
import 'partials/search.dart';

class Second extends StatelessWidget {
  final Widget child;
  Second({Key key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // I need import functions here, so I can use it on Scaffold

    new Search();

    return Scaffold(
      appBar: new AppBar(
          backgroundColor: Colors.blueAccent,
          titleSpacing: 15,
          title: _title() // like this
        ),
      ...
  }
}

但是调用函数时出现错误,请帮助我,谢谢。

最佳答案

您可以使用静态方法,也可以仅在类搜索的实例上调用该方法,并且按照惯例,两种方法 _ 仅用于命名本地方法/变量,包装类只能使用。


    class _SearchState extends State<Search> {
      String title(){
      return 'Lorem Ipsum Title';
     }

    class Second extends StatelessWidget {
    ...
      @override
      Widget build(BuildContext context) {
        Search _search = Search();
        return Scaffold(
          appBar: new AppBar(
              backgroundColor: Colors.blueAccent,
              titleSpacing: 15,
            title: _search.title() // like this
                        ),
       //...
      )}
  }


class _SearchState extends State<Search> {
   Static String title(){
      return 'Lorem Ipsum Title';
   }

   @override
   Widget build(BuildContext context) {
      //...
   }
}

class Second extends StatelessWidget {
//...
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: new AppBar(
          backgroundColor: Colors.blueAccent,
          titleSpacing: 15,
          title: Search.title() // like this
        ),
     // ...
  }
}

关于dart - 如何在 flutter 中获得其他类(class)的职能?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55527534/

10-09 04:20