0

我有两个飞镖页。[1]:https ://i.stack.imgur.com/D1xaf.png

在第二页中,我从网站上抓取了文本并将值存储在一个名为的字符串中,并使用命令在控制台命令行fetchedstring中打印字符串。print

但我希望这个字符串显示在我的主要飞镖页面中。

怎么做?

//DART FILE 1 HAS THE FOLLOWING CODE 
import 'package:flutter/material.dart';
import './function.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget 
{
@override
Widget build(BuildContext context) 
{
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(),
body: new Center(
child: new String(fetchedtext),//Here I Want The Fetched Text
),
),
);
}
}
//DART PAGE 2 HAS THE FOLLOWING CODE
import 'package:http/http.dart' as http;
import 'package:html/parser.dart' as parser;
import 'package:html/dom.dart';
mainz() async 
{
http.Response response = await http.get('https://www.google.com');    
Document document = parser.parse(response.body);
document.getElementsByTagName('a').forEach((Element element)
{
final String fetchedText = element.text;
print(fetchedText);
}
);
}
//I WANT THAT String "fetchedtext" to be displayed in my Dart Page1.
4

2 回答 2

0

如果我对您尝试做的事情的理解是正确的,那么您需要将其粘贴到function.dart文件的最后:

List get_elements() {
  http.Response response = await http.get('https://www.google.com');    
  Document document = parser.parse(response.body);
  document.getElementsByTagName('a').forEach((e) => print(e));
  return document.getElementsByTagName('a');
}

然后修改你的一行main.dart

child: get_elements().first;

请注意,如果您不想返回第一个找到的元素,只需先删除并使用 [] 选择您要获取的元素,或者如果您想获取整个列表,只需 delete .first,但随后您将得到一个细绳。

于 2018-05-17T16:14:44.150 回答
0

使用Futurebuilder

import 'package:flutter/material.dart';
import 'dart:async';
void main() => runApp(new MyApp());

class MyApp extends StatelessWidget
{
  @override
  Widget build(BuildContext context)
  {
    var builder = FutureBuilder(
      future: mainz(),
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          print(snapshot.error);
          return new Text("${snapshot.error}");
        }
        return snapshot.hasData
            ? new Center(
          child: Text(snapshot.data), //Here I Want The Fetched Text
        )
            : new CircularProgressIndicator();
      },
    );
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text("Title"),
        ),
        body: builder,
      )
    );
  }
}

Future<String>  mainz() async
{
  await new Future.delayed(new Duration(seconds: 3));
  return 'Sample data';
}
于 2018-05-22T08:16:58.927 回答